package gen.tools.deploy;

import gen.tools.Widgets;
import gen.tools.structures.S2;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class SquadInEnv extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public SquadInEnv() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		final Widgets wid = new Widgets();
		response.setCharacterEncoding(wid.UIcodeSet);
		response.setContentType("application/json");
		
		final String envId = request.getParameter("envId");
		final String subsysId = request.getParameter("subsysId");
		final int depmainSN = Integer.parseInt( request.getParameter("depmainSN") );
		
		final ArrayList<S2> squads = new ArrayList<S2>();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		try {
			final int fdepdetailid = wid.getfDepdetailid(depmainSN);	//取得細項ID
			conn = wid.getConn();
			
			String sql = "INSERT INTO fdepdetail (depmainSN,fdepdetailid,fDepActTypeId,envId,bDT) VALUES(?,?,?,?,?)";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, depmainSN);
			ps.setInt(2, fdepdetailid);
			ps.setInt(3, 1);		// 1 取得環境Server Group清單
			ps.setString(4, envId);
			ps.setTimestamp(5, wid.cDT());
			ps.execute();
			
			sql = "SELECT squadId,cip FROM mpsquadenv WHERE subsysId=? AND envId=?";
			ps = conn.prepareStatement(sql);
			ps.setString(1, subsysId);
			ps.setString(2, envId);
			rs = ps.executeQuery();
			while ( rs.next() ) {
				S2 squad = new S2();
				squad.setS1( rs.getString("squadId") );
				squad.setS2( rs.getString("cip") );
				squads.add( squad );
			}
			
			sql = "UPDATE fdepdetail SET eDT=? WHERE depmainSN=? AND fdepdetailid=?";
			ps = conn.prepareStatement(sql);
			ps.setTimestamp(1, wid.cDT() );
			ps.setInt(2, depmainSN);
			ps.setInt(3, fdepdetailid);
			ps.execute();
		} catch (Exception e) {
			wid.errLog(e);
		} finally {
			try {
				if ( rs !=null ) {rs.close();}
				if ( ps !=null ) {ps.close();}
				if ( conn !=null ) {conn.close();}
			} catch (SQLException e) {e.printStackTrace();}
		}

		response.getWriter().write( new Gson().toJson( squads ) );
	}

}
